package com.djz.tool.exception.handler;

import com.djz.tool.exception.base.BaseException;
import com.djz.tool.utils.ResponseUtils;
import com.djz.tool.wrapper.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 默认异常处理
 * @author djz
 */
@Component
@Slf4j
public class DefaultExceptionHandler implements ExceptionHandler<BaseException> {
    public static final String APPLICATION_JSON = "application/json";

    @Override
    public ResponseEntity<ResponseWrapper<Void>> handleException(HttpServletRequest request, HttpServletResponse response, Exception exception) {

        String code = "99999";
        String msg = StringUtils.isNotBlank(exception.getMessage()) ? exception.getMessage() : "系统未知异常！";

        log.error("全局捕获业务异常：[code]:{}, [msg]:{}", code, msg, exception);
        ResponseEntity<ResponseWrapper<Void>> responseWrapperResponseEntity = ResponseUtils.fail(Integer.parseInt(code), msg).toResponseEntity(HttpStatus.OK);
        return ResponseEntity.status(HttpStatus.OK).header("Content-Type", "application/json;charset=UTF-8").body(new ResponseWrapper<Void>(Integer.parseInt(code), msg, null));

    }


}
